<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { login } from '@/api/auth'
import { showToast } from 'vant'

const router = useRouter()
const userStore = useUserStore()

const loginForm = ref({
  username: '',
  password: ''
})

const onSubmit = async () => {
  try {
    const { data } = await login(loginForm.value)
    userStore.setToken(data.token)
    const userInfo = await userStore.getUserInfo()

    console.log('用户信息login:', userInfo) // 调试用
    const roleId = Number(userInfo.roleId)
    console.log('角色ID:', roleId) // 调试用

    if (roleId === 2) {
      router.replace('/doctor')
    } else if (roleId === 3) {
      router.replace('/patient')
    } else {
      router.replace('/')
    }
  } catch (error) {
    console.error('登录错误:', error) // 调试用
    showToast('登录失败：' + error.message)
  }
}
</script>
